import React, { useState, useEffect } from 'react';
import { router, withRouter } from 'umi';
import { connect } from 'umi';
import { Table, Card, Icon, Tooltip, Input, message, Popover } from 'antd';
import { useRequest } from '@/hooks';
import cn from 'classnames';
import { GuideByServerFlag, Pagination } from '@/components'
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { HighlightText } from '@/molecules';
import PopSaveCont from '@/pages/Setting/Privilege/components/PopSaveCont';
import authHelper from '@/utils/auth/helper';
import { getNewFunctionList } from '../../services';
import { AUDIT_STATUS } from '../constants';
import styles from '../index.less';

const { checkCode } = authHelper;

const NewFunctionList = ({ location, dispatch }) => {
    const { query } = location;
    const { search, pageNo, pageSize = 10 } = query;

    const [dataSource, setDataSource] = useState([]);
    const [total, setTotal] = useState(0);

    // 获取列表数据
    const { run: fetchNewFunctionList, loading } = useRequest(params => getNewFunctionList(params), {
        manual: true,
        onSuccess: ({ msg, code, data }) => {
            if (code === 10000) {
                const { rows = [], total: dataTotal = 0 } = data;
                setTotal(dataTotal);
                setDataSource(rows);
            } else {
                message.error(msg);
            }
        }
    });

    useEffect(() => {
        dispatch({
            type: 'global/fetchNewFunctionCount',
            callback: newFunctionCount => {
                dispatch({
                    type: 'menu/saveMenu',
                    payload: {
                        count: newFunctionCount.data,
                        path: '/setting/privilege/newFunctionList'
                    }
                });
            }
        });
    }, [dispatch]);

    useEffect(() => {
        const params = { nameZh: '', pageNo: query.pageNo, pageSize: query.pageSize };
        if (search) {
            params.nameZh = search;
        }
        fetchNewFunctionList(params);
    }, [fetchNewFunctionList, query, search]);

    // 链接至详情页
    const handleLinkToDetail = (event, code, status) => {
        event.stopPropagation();
        if (checkCode('system:authorization:new:detail')) {
            history.push({
                pathname: '/setting/privilege/newFunctionList/detail',
                query: { resourceCode: code, auditStatus: status }
            });
        }
    };

    // 链接至配置页面
    const handleLinkToDeploy = (code, status) => {
        const isDisabled = status === 1 || status === 2;
        if (isDisabled || !checkCode('system:authorization:new:edit')) {
            return;
        }
        history.push({
            pathname: '/setting/privilege/newFunctionDeploy',
            query: { resourceCode: code, auditStatus: status }
        });
    };

    const columns = [
        {
            title: '功能',
            dataIndex: 'nameZh',
            width: 300,
            render: (value, record) => {
                const { isRead, auditStatus, resourceCode } = record;
                return (
                    <span
                        className={`${!isRead ? styles.unread : styles.read} ${
                            checkCode('system:authorization:new:detail') ? '' : styles.noAuth
                        }`}
                        onClick={event => handleLinkToDetail(event, resourceCode, auditStatus)}
                    >
                        <HighlightText keywords={search ? [search] : []}>{value}</HighlightText>
                        {record.isDraft > 0 && (
                            <Popover content={<PopSaveCont draft={{ updateTime: record.draftTime }} />} trigger="hover">
                                <Icon type="info-circle" style={{ marginLeft: 4 }} />
                            </Popover>
                        )}
                    </span>
                );
            }
        },
        {
            title: () => (
                <div className={styles.newFunctionTableHeader}>
                    <div>子功能</div>
                    <ul>
                        <li>菜单</li>
                        <li>模块</li>
                        <li>页面</li>
                        <li>按钮</li>
                    </ul>
                </div>
            ),
            dataIndex: 'resourceTypeNum',
            width: 250,
            render: (value = {}) => {
                const { menu: menuCount, module: moduleCount, page: pageCount, button: buttonCount } = value;
                return (
                    <div className={styles.functionIncidenceWrapper}>
                        <span>{menuCount > 0 ? menuCount : '-'}</span>
                        <span>{moduleCount > 0 ? moduleCount : '-'}</span>
                        <span>{pageCount > 0 ? pageCount : '-'}</span>
                        <span>{buttonCount > 0 ? buttonCount : '-'}</span>
                    </div>
                );
            }
        },
        {
            title: '上线说明',
            dataIndex: 'onlineRemarkZh',
            // width: 532,
            render: value => (
                <div className={styles.releaseDescribe} title={value}>
                    {value}
                </div>
            )
        },
        {
            title: '上线时间',
            dataIndex: 'onlineTime',
            width: 200
        },
        {
            title: '状态',
            dataIndex: 'auditStatus',
            width: 100,
            render: value => <span className={`auditStatus-${value}`}>{AUDIT_STATUS[value]}</span>
        },
        {
            title: '操作',
            dataIndex: 'action',
            width: 200,
            render: (value, record) => {
                const { auditStatus, resourceCode } = record;
                const isDisabled = auditStatus === 1 || auditStatus === 2;
                return (
                    <div className={styles.tableAction}>
                        <Tooltip title="查看详情">
                            <i
                                className={cn('iconfont iconlistfunction_viewinterview_icon_default', styles.icon)}
                                onClick={event => handleLinkToDetail(event, resourceCode, auditStatus)}
                                disabled={!checkCode('system:authorization:new:detail')}
                            />
                        </Tooltip>
                        <Tooltip title="配置权限">
                            <i
                                className={cn('iconfont iconlistfunction_edit_icon_default', styles.icon)}
                                disabled={isDisabled || !checkCode('system:authorization:new:edit')}
                                onClick={() => handleLinkToDeploy(resourceCode, auditStatus)}
                            />
                        </Tooltip>
                    </div>
                );
            }
        }
    ];

    const handlePaginationChange = pagination => {
        const { current, pageSize: ps } = pagination;
        history.replace({ query: { ...query, pageNo: current, pageSize: ps } });
    };

    // 搜索
    const handleSearch = value => {
        history.replace({ query: { ...query, search: value, pageNo: 1 } });
    };

    return (
        <PageHeaderWrapper>
            <GuideByServerFlag serverStorageKey="guideNewFunctionList">
                <Card
                    title={
                        <GuideByServerFlag.Step
                            placement="rightTop"
                            title="【新功能】板块"
                            content="可查看上线的新功能，并进行启用及配置"
                        >
                            <span>新功能</span>
                        </GuideByServerFlag.Step>
                    }
                >
                    <div className={styles.newFunctionSearchWrapper}>
                        <Input.Search
                            placeholder="搜索新功能名称"
                            defaultValue={search}
                            onSearch={handleSearch}
                            style={{ width: 240 }}
                        />
                    </div>
                    <div className={styles.newFunctionListWrapper}>
                        <Table
                            className={styles.functionListTable}
                            columns={columns}
                            rowKey="resourceCode"
                            dataSource={dataSource}
                            pagination={false}
                        />
                        <Pagination
                            current={pageNo || 1}
                            pageSize={pageSize || 10}
                            loading={loading}
                            total={total}
                            onChange={handlePaginationChange}
                        />
                    </div>
                </Card>
            </GuideByServerFlag>
        </PageHeaderWrapper>
    );
};

export default connect()(withRouter(NewFunctionList));
